-- seckill_ultra.lua
local voucherId = ARGV[1];
local userId = ARGV[2];
local timestamp = ARGV[3];

-- 使用Hash结构，确保同节点存储
local voucherKey = "seckill:{voucher:" .. voucherId .. "}";

-- 原子性检查 + 扣减 + 记录
local stock = redis.call("hget", voucherKey, "stock");
if (tonumber(stock) <= 0) then
    return 1; -- 库存不足
end

local isOrdered = redis.call("hexists", voucherKey, "user:" .. userId);
if (isOrdered == 1) then
    return 2; -- 已下单
end

-- 原子性操作
redis.call("hincrby", voucherKey, "stock", -1);
redis.call("hset", voucherKey, "user:" .. userId, timestamp);

-- 写入高性能Stream
redis.call("xadd", "seckill:orders", "*",
    "userId", userId,
    "voucherId", voucherId,
    "timestamp", timestamp
);

return 0;